<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.2">
  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/icon.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/icon.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/icon.png">
  <link rel="mask-icon" href="/blog/images/icon.svg" color="#222">

<link rel="stylesheet" href="/blog/css/main.css">


<link rel="stylesheet" href="/blog/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"bgape002.gitee.io","root":"/blog/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"mac"},"back2top":{"enable":true,"sidebar":false,"scrollpercent":true},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="异常概述异常机制是衡量一个编程语言是否成熟的标准之一，使用异常处理机制的python程序容错性会更好。 什么是异常 在自动化脚本开发程中，往往会出现一些不可预知的错误,这种情况在编程语言中叫做异常。遇到异常，我们要处理它，不是等到异常发生的时候，让IDE帮你处理，等他给你抛出异常的时候，就晚了。当Python脚本发生异常时我们需要捕获处理它，否则程序会终止执行。 python的异常机制主要依赖tr">
<meta property="og:type" content="article">
<meta property="og:title" content="python异常处理">
<meta property="og:url" content="https://bgape002.gitee.io/2022/08/04/python%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86/index.html">
<meta property="og:site_name" content="bgape002">
<meta property="og:description" content="异常概述异常机制是衡量一个编程语言是否成熟的标准之一，使用异常处理机制的python程序容错性会更好。 什么是异常 在自动化脚本开发程中，往往会出现一些不可预知的错误,这种情况在编程语言中叫做异常。遇到异常，我们要处理它，不是等到异常发生的时候，让IDE帮你处理，等他给你抛出异常的时候，就晚了。当Python脚本发生异常时我们需要捕获处理它，否则程序会终止执行。 python的异常机制主要依赖tr">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-08-04T06:35:25.000Z">
<meta property="article:modified_time" content="2022-08-04T08:42:46.486Z">
<meta property="article:author" content="bgape002">
<meta property="article:tag" content="异常处理&#x2F;exception">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://bgape002.gitee.io/2022/08/04/python%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>python异常处理 | bgape002</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/blog/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">bgape002</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">淡泊明志，宁静致远</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/blog/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/blog/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">66</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/blog/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">27</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blog/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">61</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://bgape002.gitee.io/2022/08/04/python%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/head.png">
      <meta itemprop="name" content="bgape002">
      <meta itemprop="description" content="mail: bgape002@163.com">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="bgape002">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          python异常处理
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2022-08-04 14:35:25 / 修改时间：16:42:46" itemprop="dateCreated datePublished" datetime="2022-08-04T14:35:25+08:00">2022-08-04</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/python/" itemprop="url" rel="index"><span itemprop="name">python</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/blog/2022/08/04/python%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/blog/2022/08/04/python%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h3 id="异常概述"><a href="#异常概述" class="headerlink" title="异常概述"></a>异常概述</h3><p>异常机制是衡量一个编程语言是否成熟的标准之一，使用异常处理机制的python程序容错性会更好。</p>
<h3 id="什么是异常"><a href="#什么是异常" class="headerlink" title="什么是异常"></a>什么是异常</h3><ul>
<li>在自动化脚本开发程中，往往会出现一些不可预知的错误,这种情况在编程语言中叫做异常。遇到异常，我们要处理它，不是等到异常发生的时候，让IDE帮你处理，等他给你抛出异常的时候，就晚了。当Python脚本发生异常时我们需要捕获处理它，否则程序会终止执行。</li>
<li>python的异常机制主要依赖try、except、else、finally和raise五个关键字，其中在try关键字后缩进的代码块简称try块，它里面放置的是可能引发异常的代码</li>
</ul>
<span id="more"></span>

<h3 id="异常处理规则"><a href="#异常处理规则" class="headerlink" title="异常处理规则"></a>异常处理规则</h3><ul>
<li><strong>异常处理目的</strong><ol>
<li>使程序代码混乱最小化</li>
<li>捕获并保留诊断信息</li>
<li>通知相关人员</li>
<li>采用合适的方法结束异常</li>
</ol>
</li>
<li><strong>异常处理规则</strong><ol>
<li>不要过度使用异常<ul>
<li>不要把异常和普通错误混淆在一起。不再编写任何错误处理代码，而是以简单地引发异常来代替所有的错误处理</li>
<li>不要使用异常处理来代替正常的程序流程控制</li>
</ul>
</li>
<li>不要使用庞大的try块<ul>
<li>把大块的 try 块分割成多个可能出现异常的程序段落，并把它们放在单独的 try块中，从而分别捕获并处理异常</li>
</ul>
</li>
<li>不要忽略捕捉到的异常，可以对异常采取适当措施</li>
</ol>
</li>
</ul>
<h3 id="常见的内置异常"><a href="#常见的内置异常" class="headerlink" title="常见的内置异常"></a>常见的内置异常</h3><figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">AttributeError			<span class="comment">/* 试图访问一个对象不存在的属性 */</span></span><br><span class="line">IOError					<span class="comment">/* 输入/输出异常 */</span></span><br><span class="line">ImportError				<span class="comment">/* 引入模块或包异常（路径问题或名称问题） */</span></span><br><span class="line">IndentationError		<span class="comment">/* 缩进错误 */</span></span><br><span class="line">IndexError				<span class="comment">/* 下标索引错误 */</span></span><br><span class="line">KeyError				<span class="comment">/* 所访问键值不存在 */</span></span><br><span class="line">KeyboardInterrupt		<span class="comment">/* Ctrl+C被按下（键盘终止输入） */</span></span><br><span class="line">NameError				<span class="comment">/* 使用未定义的变量 */</span></span><br><span class="line">SyntaxError				<span class="comment">/* 语法错误 */</span></span><br><span class="line">TypeError				<span class="comment">/* 传入对象的类型与要求的不符合 */</span></span><br><span class="line">UnboundLocalError		<span class="comment">/* 试图访问一个还未被设置的局部变量 */</span></span><br><span class="line">ValueError				<span class="comment">/* 传入一个调用者不期望的值 */</span></span><br></pre></td></tr></table></figure>



<h3 id="内置异常类的层次结构"><a href="#内置异常类的层次结构" class="headerlink" title="内置异常类的层次结构"></a>内置异常类的层次结构</h3><figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br></pre></td><td class="code"><pre><span class="line">BaseException  # 所有异常的基类</span><br><span class="line"> +-- SystemExit  # 解释器请求退出</span><br><span class="line"> +-- KeyboardInterrupt  # 用户中断执行(通常是输入^C)</span><br><span class="line"> +-- GeneratorExit  # 生成器(generator)发生异常来通知退出</span><br><span class="line"> +-- Exception  # 常规异常的基类</span><br><span class="line">      +-- StopIteration  # 迭代器没有更多的值</span><br><span class="line">      +-- StopAsyncIteration  # 必须通过异步迭代器对象的__anext__()方法引发以停止迭代</span><br><span class="line">      +-- ArithmeticError  # 各种算术错误引发的内置异常的基类</span><br><span class="line">      |    +-- FloatingPointError  # 浮点计算错误</span><br><span class="line">      |    +-- OverflowError  # 数值运算结果太大无法表示</span><br><span class="line">      |    +-- ZeroDivisionError  # 除(或取模)零 (所有数据类型)</span><br><span class="line">      +-- AssertionError  # 当assert语句失败时引发</span><br><span class="line">      +-- AttributeError  # 属性引用或赋值失败</span><br><span class="line">      +-- BufferError  # 无法执行与缓冲区相关的操作时引发</span><br><span class="line">      +-- EOFError  # 当<span class="selector-tag">input</span>()函数在没有读取任何数据的情况下达到文件结束条件(EOF)时引发</span><br><span class="line">      +-- ImportError  # 导入模块/对象失败</span><br><span class="line">      |    +-- ModuleNotFoundError  # 无法找到模块或在在sys<span class="selector-class">.modules</span>中找到<span class="attribute">None</span></span><br><span class="line">      +-- LookupError  # 映射或序列上使用的键或索引无效时引发的异常的基类</span><br><span class="line">      |    +-- IndexError  # 序列中没有此索引(index)</span><br><span class="line">      |    +-- KeyError  # 映射中没有这个键</span><br><span class="line">      +-- MemoryError  # 内存溢出错误(对于Python 解释器不是致命的)</span><br><span class="line">      +-- NameError  # 未声明/初始化对象 (没有属性)</span><br><span class="line">      |    +-- UnboundLocalError  # 访问未初始化的本地变量</span><br><span class="line">      +-- OSError  # 操作系统错误，EnvironmentError，IOError，WindowsError，socket<span class="selector-class">.error</span>，select<span class="selector-class">.error</span>和mmap<span class="selector-class">.error</span>已合并到OSError中，构造函数可能返回子类</span><br><span class="line">      |    +-- BlockingIOError  # 操作将阻塞对象(e<span class="selector-class">.g</span>. socket)设置为非阻塞操作</span><br><span class="line">      |    +-- ChildProcessError  # 在子进程上的操作失败</span><br><span class="line">      |    +-- ConnectionError  # 与连接相关的异常的基类</span><br><span class="line">      |    |    +-- BrokenPipeError  # 另一端关闭时尝试写入管道或试图在已关闭写入的套接字上写入</span><br><span class="line">      |    |    +-- ConnectionAbortedError  # 连接尝试被对等方中止</span><br><span class="line">      |    |    +-- ConnectionRefusedError  # 连接尝试被对等方拒绝</span><br><span class="line">      |    |    +-- ConnectionResetError    # 连接由对等方重置</span><br><span class="line">      |    +-- FileExistsError  # 创建已存在的文件或目录</span><br><span class="line">      |    +-- FileNotFoundError  # 请求不存在的文件或目录</span><br><span class="line">      |    +-- InterruptedError  # 系统调用被输入信号中断</span><br><span class="line">      |    +-- IsADirectoryError  # 在目录上请求文件操作(例如 os<span class="selector-class">.remove</span>())</span><br><span class="line">      |    +-- NotADirectoryError  # 在不是目录的事物上请求目录操作(例如 os<span class="selector-class">.listdir</span>())</span><br><span class="line">      |    +-- PermissionError  # 尝试在没有足够访问权限的情况下运行操作</span><br><span class="line">      |    +-- ProcessLookupError  # 给定进程不存在</span><br><span class="line">      |    +-- TimeoutError  # 系统函数在系统级别超时</span><br><span class="line">      +-- ReferenceError  # weakref<span class="selector-class">.proxy</span>()函数创建的弱引用试图访问已经垃圾回收了的对象</span><br><span class="line">      +-- RuntimeError  # 在检测到不属于任何其他类别的错误时触发</span><br><span class="line">      |    +-- NotImplementedError  # 在用户定义的基类中，抽象方法要求派生类重写该方法或者正在开发的类指示仍然需要添加实际实现</span><br><span class="line">      |    +-- RecursionError  # 解释器检测到超出最大递归深度</span><br><span class="line">      +-- SyntaxError  # Python 语法错误</span><br><span class="line">      |    +-- IndentationError  # 缩进错误</span><br><span class="line">      |         +-- TabError  # Tab和空格混用</span><br><span class="line">      +-- SystemError  # 解释器发现内部错误</span><br><span class="line">      +-- TypeError  # 操作或函数应用于不适当类型的对象</span><br><span class="line">      +-- ValueError  # 操作或函数接收到具有正确类型但值不合适的参数</span><br><span class="line">      |    +-- UnicodeError  # 发生与Unicode相关的编码或解码错误</span><br><span class="line">      |         +-- UnicodeDecodeError  # Unicode解码错误</span><br><span class="line">      |         +-- UnicodeEncodeError  # Unicode编码错误</span><br><span class="line">      |         +-- UnicodeTranslateError  # Unicode转码错误</span><br><span class="line">      +-- Warning  # 警告的基类</span><br><span class="line">           +-- DeprecationWarning  # 有关已弃用功能的警告的基类</span><br><span class="line">           +-- PendingDeprecationWarning  # 有关不推荐使用功能的警告的基类</span><br><span class="line">           +-- RuntimeWarning  # 有关可疑的运行时行为的警告的基类</span><br><span class="line">           +-- SyntaxWarning  # 关于可疑语法警告的基类</span><br><span class="line">           +-- UserWarning  # 用户代码生成警告的基类</span><br><span class="line">           +-- FutureWarning  # 有关已弃用功能的警告的基类</span><br><span class="line">           +-- ImportWarning  # 关于模块导入时可能出错的警告的基类</span><br><span class="line">           +-- UnicodeWarning  # 与Unicode相关的警告的基类</span><br><span class="line">           +-- BytesWarning  # 与bytes和bytearray相关的警告的基类</span><br><span class="line">           +-- ResourceWarning  # 与资源使用相关的警告的基类。被默认警告过滤器忽略。</span><br><span class="line"> </span><br></pre></td></tr></table></figure>



<h3 id="基本语法结构"><a href="#基本语法结构" class="headerlink" title="基本语法结构"></a>基本语法结构</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span>:</span><br><span class="line">    程序执行语句块</span><br><span class="line"><span class="keyword">except</span> Exception <span class="keyword">as</span> alias:</span><br><span class="line">    异常处理语句块</span><br><span class="line">...</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    无异常时处理语句块</span><br><span class="line"><span class="keyword">finally</span>:</span><br><span class="line">    必须的处理语句块</span><br></pre></td></tr></table></figure>



<h3 id="基础样例"><a href="#基础样例" class="headerlink" title="基础样例"></a>基础样例</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">正常状态下，程序的退出码(exit code)为 0</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">try</span>:</span><br><span class="line">    a = <span class="number">10</span> / <span class="number">0</span>			<span class="comment"># 此处异常，try包裹的剩下（两行）代码都不会执行，直接跳到对应的异常处理分支</span></span><br><span class="line">    a = b + <span class="number">1</span></span><br><span class="line">    a = <span class="number">2</span> + <span class="string">&#x27;2&#x27;</span></span><br><span class="line"><span class="keyword">except</span> (NameError, ZeroDivisionError) <span class="keyword">as</span> e:</span><br><span class="line">    <span class="built_in">print</span>(<span class="built_in">type</span>(e), e)</span><br><span class="line"><span class="keyword">except</span> TypeError <span class="keyword">as</span> e:</span><br><span class="line">    <span class="built_in">print</span>(<span class="built_in">type</span>(e), e)</span><br><span class="line"><span class="keyword">except</span> Exception <span class="keyword">as</span> e:</span><br><span class="line">    <span class="built_in">print</span>(e)</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&#x27;else&#x27;</span>)</span><br><span class="line"><span class="keyword">finally</span>:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&#x27;finally&#x27;</span>)</span><br></pre></td></tr></table></figure>



<h3 id="raise-主动抛出异常"><a href="#raise-主动抛出异常" class="headerlink" title="raise 主动抛出异常"></a>raise 主动抛出异常</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span>:</span><br><span class="line">    dct = &#123;<span class="string">&#x27;a&#x27;</span>:<span class="number">1</span>&#125;</span><br><span class="line">    inp = <span class="built_in">input</span>(<span class="string">&quot;input a value:&quot;</span>)</span><br><span class="line">    <span class="keyword">if</span> <span class="built_in">len</span>(inp)&gt;<span class="number">1</span> :</span><br><span class="line">       <span class="keyword">raise</span> ValueError(<span class="string">&#x27;输入字符过长&#x27;</span>)		<span class="comment"># 主动抛出一个异常，后面的except分支会进行捕获</span></span><br><span class="line">    a = <span class="number">2</span> / <span class="built_in">int</span>(inp)</span><br><span class="line">    a = dct[inp]</span><br><span class="line"><span class="keyword">except</span> (NameError, ZeroDivisionError) <span class="keyword">as</span> e:</span><br><span class="line">    <span class="built_in">print</span>(<span class="built_in">type</span>(e), e)</span><br><span class="line">    <span class="keyword">raise</span>						<span class="comment"># raise不带参数且处于except块中，将会自动引发当前上下文激活的异常</span></span><br><span class="line">        						<span class="comment"># 否则，通常默认引发RuntimeError异常</span></span><br><span class="line"><span class="keyword">except</span> TypeError <span class="keyword">as</span> e:</span><br><span class="line">    <span class="built_in">print</span>(<span class="built_in">type</span>(e), e)</span><br><span class="line"><span class="keyword">except</span> Exception <span class="keyword">as</span> e:</span><br><span class="line">    <span class="built_in">print</span>(e)</span><br><span class="line">    <span class="keyword">raise</span> KeyError(<span class="string">&#x27;所访问键值不存在&#x27;</span>)		<span class="comment"># 指明主动抛出的异常类型</span></span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&#x27;else&#x27;</span>)</span><br><span class="line"><span class="keyword">finally</span>:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&#x27;finally&#x27;</span>)</span><br></pre></td></tr></table></figure>



<h3 id="自定义异常"><a href="#自定义异常" class="headerlink" title="自定义异常"></a>自定义异常</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">&quot;&quot;&quot;自定义异常</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">TranError</span>(<span class="title class_ inherited__">Exception</span>):</span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__init__</span>(<span class="params">self, errCode=<span class="number">500</span>, message=<span class="string">&#x27;ranError&#x27;</span></span>):</span><br><span class="line">        self.errrorCode = errCode</span><br><span class="line">        self.message = message</span><br><span class="line">        </span><br><span class="line">    <span class="keyword">def</span> <span class="title function_">__str__</span>(<span class="params">self</span>):</span><br><span class="line">        <span class="keyword">return</span> <span class="string">f&#x27;[<span class="subst">&#123;self.errrorCode&#125;</span>]: <span class="subst">&#123;self.message&#125;</span>&#x27;</span></span><br><span class="line">    </span><br><span class="line"></span><br><span class="line"><span class="keyword">try</span>:</span><br><span class="line">    dct = &#123;<span class="string">&#x27;a&#x27;</span>:<span class="number">1</span>&#125;</span><br><span class="line">    inp = <span class="built_in">input</span>(<span class="string">&quot;input a value:&quot;</span>)</span><br><span class="line">    <span class="keyword">if</span> <span class="built_in">len</span>(inp)&gt;<span class="number">1</span> :</span><br><span class="line">       <span class="keyword">raise</span> TranError(<span class="number">505</span>, <span class="string">&quot;自定义异常&quot;</span>)		<span class="comment"># 主动抛出一个异常，后面的except分支会进行捕获</span></span><br><span class="line">    a = <span class="number">2</span> / <span class="built_in">int</span>(inp)</span><br><span class="line">    a = dct[inp]</span><br><span class="line"><span class="keyword">except</span> (NameError, ZeroDivisionError) <span class="keyword">as</span> e:</span><br><span class="line">    <span class="built_in">print</span>(<span class="built_in">type</span>(e), e)</span><br><span class="line">    <span class="keyword">raise</span>						<span class="comment"># 不带参数，则抛出之前捕获到的异常，给调用者处理</span></span><br><span class="line"><span class="keyword">except</span> TypeError <span class="keyword">as</span> e:</span><br><span class="line">    <span class="built_in">print</span>(<span class="built_in">type</span>(e), e)</span><br><span class="line"><span class="keyword">except</span> Exception <span class="keyword">as</span> e:</span><br><span class="line">    <span class="built_in">print</span>(e)</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&#x27;else&#x27;</span>)</span><br><span class="line"><span class="keyword">finally</span>:</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">&#x27;finally&#x27;</span>)</span><br><span class="line">    </span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot; output</span></span><br><span class="line"><span class="string">input a value:aa</span></span><br><span class="line"><span class="string">[505]: 自定义异常</span></span><br><span class="line"><span class="string">finally</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">Process finished with exit code 0</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>








<h3 id="参考链接"><a href="#参考链接" class="headerlink" title="参考链接"></a>参考链接</h3><font size=2>

<p>[1] <a target="_blank" rel="noopener" href="https://www.bilibili.com/video/BV1Fg4y1z7eP?p=16&vd_source=5f03bdbb9a8460c7ae08f9cdea23577b">异常和程序调试</a></p>
<p>[2] <a target="_blank" rel="noopener" href="https://blog.csdn.net/weixin_42684559/article/details/119441492">python中的异常处理-上篇</a></p>
<p>[3] <a target="_blank" rel="noopener" href="https://blog.csdn.net/weixin_42684559/article/details/119783788?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522165959745316781647517967%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fblog.%2522%257D&request_id=165959745316781647517967&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~first_rank_ecpm_v1~rank_v31_ecpm-2-119783788-null-null.nonecase&utm_term=%E5%BC%82%E5%B8%B8&spm=1018.2226.3001.4450">python中的异常处理-下篇</a></p>
</font>


    </div>

    
    
    

      <footer class="post-footer">
          
          <div class="post-tags">
              <a href="/blog/tags/%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86-exception/" rel="tag"><i class="fa fa-tag"></i> 异常处理/exception</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blog/2022/07/28/%E7%BA%A2%E9%BB%91%E6%A0%91/" rel="prev" title="红黑树">
      <i class="fa fa-chevron-left"></i> 红黑树
    </a></div>
      <div class="post-nav-item">
    <a href="/blog/2022/08/05/socket%E7%BC%96%E7%A8%8B/" rel="next" title="socket编程">
      socket编程 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>


        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%BC%82%E5%B8%B8%E6%A6%82%E8%BF%B0"><span class="nav-number">1.</span> <span class="nav-text">异常概述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BB%80%E4%B9%88%E6%98%AF%E5%BC%82%E5%B8%B8"><span class="nav-number">2.</span> <span class="nav-text">什么是异常</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86%E8%A7%84%E5%88%99"><span class="nav-number">3.</span> <span class="nav-text">异常处理规则</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%B8%B8%E8%A7%81%E7%9A%84%E5%86%85%E7%BD%AE%E5%BC%82%E5%B8%B8"><span class="nav-number">4.</span> <span class="nav-text">常见的内置异常</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%86%85%E7%BD%AE%E5%BC%82%E5%B8%B8%E7%B1%BB%E7%9A%84%E5%B1%82%E6%AC%A1%E7%BB%93%E6%9E%84"><span class="nav-number">5.</span> <span class="nav-text">内置异常类的层次结构</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%9F%BA%E6%9C%AC%E8%AF%AD%E6%B3%95%E7%BB%93%E6%9E%84"><span class="nav-number">6.</span> <span class="nav-text">基本语法结构</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%9F%BA%E7%A1%80%E6%A0%B7%E4%BE%8B"><span class="nav-number">7.</span> <span class="nav-text">基础样例</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#raise-%E4%B8%BB%E5%8A%A8%E6%8A%9B%E5%87%BA%E5%BC%82%E5%B8%B8"><span class="nav-number">8.</span> <span class="nav-text">raise 主动抛出异常</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E5%BC%82%E5%B8%B8"><span class="nav-number">9.</span> <span class="nav-text">自定义异常</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8F%82%E8%80%83%E9%93%BE%E6%8E%A5"><span class="nav-number">10.</span> <span class="nav-text">参考链接</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="bgape002"
      src="/blog/images/head.png">
  <p class="site-author-name" itemprop="name">bgape002</p>
  <div class="site-description" itemprop="description">mail: bgape002@163.com</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">61</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/blog/categories/">
          
        <span class="site-state-item-count">27</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/blog/tags/">
          
        <span class="site-state-item-count">66</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2021 – 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">bgape002</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/blog/lib/anime.min.js"></script>
  <script src="/blog/lib/velocity/velocity.min.js"></script>
  <script src="/blog/lib/velocity/velocity.ui.min.js"></script>

<script src="/blog/js/utils.js"></script>

<script src="/blog/js/motion.js"></script>


<script src="/blog/js/schemes/pisces.js"></script>


<script src="/blog/js/next-boot.js"></script>




  




  
<script src="/blog/js/local-search.js"></script>











<script>
if (document.querySelectorAll('pre.mermaid').length) {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js', () => {
    mermaid.initialize({
      theme    : 'forest',
      logLevel : 3,
      flowchart: { curve     : 'linear' },
      gantt    : { axisFormat: '%m/%d/%Y' },
      sequence : { actorMargin: 50 }
    });
  }, window.mermaid);
}
</script>


  

  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : false,
      appId      : 'szhBf0Qamzsowubi1WnkXmUj-gzGzoHsz',
      appKey     : 'WpwxoK0fVJHvhzWwakr9vbpA',
      placeholder: "Just go go",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : false,
      lang       : '' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

</body>
</html>
